package com.hehua.InterpreterPattern;

import java.util.Stack;

/**
 * 指令处理类
 */
public class InstructionHandler {
    private AbstractNode node;

    public void handle(String instruction){
        AbstractNode left = null,right =null;
        AbstractNode direction = null,action =null,distance =null;
        /**
         * 声明一个栈用于存储抽象语法树
         */
        Stack<AbstractNode> stack = new Stack<>();
        /**
         * 以空格分隔指令字符串
         */
        String[] words = instruction.split(" ");
        for (int i = 0; i < words.length; i++) {
            /**
             * 本实例采用栈的方式处理指令,如果遇到and则将其后的3个单词作为3个终结符表达式连成一个简单的句子
             * SentenceNode作为and的右表达式,而将从栈顶弹出的表达式作为and的左表达式,最后将新的and的表达式压入栈中
             */
            if (words[i].equalsIgnoreCase("and")){
                left = stack.pop();
                String word1 = words[++i];
                direction = new DirectionNode(word1);
                String word2 = words[++i];
                action = new ActionNode(word2);
                String word3 = words[++i];
                distance = new DistanceNode(word3);
                right = new SentenceNode(direction,action,distance);
                stack.push(new AndNode(left,right));
            }else {
                /**
                 * 如果是从头开始解释,则将前3个单词组成一个简单的句子 SentenceNode并将该句子压入栈中
                 */
                String word1 = words[i];
                direction = new DirectionNode(word1);
                String word2 = words[++i];
                action = new ActionNode(word2);
                String word3 = words[++i];
                distance = new DistanceNode(word3);
                left = new SentenceNode(direction,action,distance);
                stack.push(left);
            }
        }
        //将全部表达式从栈中弹出
        this.node = stack.pop();

    }
    public String output(){
        //解释表达式
        String result = node.interpret();
        return result;
    }
}
